package com.xm.springboot.component;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义登录拦截器
 *
 * @author xiaoming
 * @date 2020-08-08 16:58
 */
public class MyLoginHandlerInterceptor implements HandlerInterceptor {
    /**
     * 连接器几个方法的顺序
     * preHandle 1
     * preHandle 2
     *               Controller
     * postHandle 1
     * postHandle 2
     * afterHandle
     */

    /**
     * 目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null) {
            // 未登录: 返回登录页面
            request.setAttribute("msg", "没有权限, 请先登录");
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        } else {
            request.setAttribute("username", user);
            // 已登录: 放行请求
            return true;
        }

    }

}
